<template>
  <AuModal
    :key="rowData?.formulaId"
    v-model="showDetailModal"
    :title="t('formulaDetail.title')"
    width="812"
    height="90vh"
    :padding="false"
    @close="close"
    @handleConfirm="handleConfirm"
  >
    <div class="py-[16px] px-[20px] border-b-[1px] border-[#EAEBEF]">
      <AuForm
        ref="formHxtRef"
        class="formula-form"
        :formList="formList"
        :hiddenBtn="true"
        :formData="formData"
      />
    </div>
    <el-tabs
      v-model="editableTabsValue"
      v-loading="loading"
      editable
      class="demo-tabs mt-2"
      @edit="handleTabsEdit"
    >
      <template #add-icon>
        <el-link :underline="false" type="primary">
          <iconify-icon-online icon="ep:plus" />&nbsp;{{
            t("formulaDetail.addSpec")
          }}
        </el-link>
      </template>
      <el-tab-pane
        v-for="item in hxtFormulaSpecDetailList"
        :key="item.specId"
        :label="item.specName"
        :name="item.specId"
      >
        <template #label>
          <span>
            {{ te(item.specName) ? t(item.specName) : item.specName }}
          </span>
          <el-link type="primary" :underline="false" @click="tabsDbClick(item)">
            <component
              :is="useRenderIcon(Edit)"
              class="text-[16px] ml-1 mt-[1px]"
            />
          </el-link>
        </template>

        <el-scrollbar wrap-class="p-[20px]" height="calc(90vh - 350px)">
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="t('formulaDetail.externalId')"
                prop="thirdValue"
                label-width="auto"
              >
                <el-input
                  v-model="item.thirdValue"
                  class="!w-[94%]"
                  :maxlength="20"
                  :placeholder="t('formulaDetail.externalIdPlaceholder')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('formulaDetail.teaAmount')"
                prop="materialW"
                label-width="auto"
              >
                <el-input
                  v-model="item.materialW"
                  class="!w-[94%]"
                  :maxlength="10"
                  :placeholder="t('formulaDetail.teaAmountPlaceholder')"
                  @input="handleTimeInput('materialW', item, $event)"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div
            v-for="(spec, index) in item.hxtFormulaDetailList"
            :key="index"
            class="bg-[#F5F9FF] rounded-[2px] px-[16px] py-[20px] mt-[16px] first:mt-0"
          >
            <div class="flex justify-between">
              <div class="text-[#242930] text-[14px]">
                {{ t("formulaDetail.section", { index: index + 1 }) }}
              </div>
              <el-button
                link
                class="!text-[#EA2626] !text-[12px] !hover:text-[#ea4949]"
                @click="removeSpec(item, index)"
              >
                <component
                  :is="useRenderIcon(Delete)"
                  class="text-[12px] ml-1 mt-[1px]"
                />
                <span class="inline-block align-middle"
                  >&nbsp;{{ t("buttons.delete") }}</span
                >
              </el-button>
            </div>

            <div class="mt-[20px]">
              <el-form
                ref="specFormRef"
                :model="spec"
                :rules="specRules"
                class="formula-inForm"
                inline
                label-width="140px"
              >
                <el-form-item
                  :label="t('formulaDetail.waterVolume')"
                  prop="waterValue"
                >
                  <el-input
                    v-model="spec.waterValue"
                    :maxlength="10"
                    :placeholder="t('formulaDetail.waterVolumePlaceholder')"
                    @input="handleInput('waterValue', spec, 5000)"
                    @blur="handleBlur('waterValue', spec, 100)"
                  />
                </el-form-item>
                <el-form-item
                  :label="t('formulaDetail.temperature')"
                  prop="temp"
                >
                  <el-input
                    v-model="spec.temp"
                    :maxlength="10"
                    :placeholder="t('formulaDetail.temperaturePlaceholder')"
                    @input="handleInput('temp', spec, 97)"
                    @blur="handleBlur('temp', spec, 70)"
                  />
                </el-form-item>
                <el-form-item :label="t('formulaDetail.brewTime')" prop="time">
                  <el-input
                    v-model="spec.time"
                    :maxlength="10"
                    :placeholder="t('formulaDetail.brewTimePlaceholder')"
                    @input="handleInput('time', spec, 3600)"
                    @blur="handleBlur('time', spec, 60)"
                  />
                </el-form-item>
                <el-form-item
                  :label="t('formulaDetail.stirSwitch')"
                  prop="switchStir"
                >
                  <el-switch
                    v-model="spec.switchStir"
                    active-value="1"
                    inactive-value="0"
                    @change="switchStirHandle(spec, $event)"
                  />
                </el-form-item>
                <el-form-item
                  class="justify-between"
                  :label="t('formulaDetail.iceSwitch')"
                  prop="iceWeight"
                >
                  <el-input
                    v-model="spec.iceWeight"
                    class="!w-[70%]"
                    :disabled="spec.iceSwitch == '0'"
                    :maxlength="10"
                    :placeholder="t('formulaDetail.iceWeightPlaceholder')"
                    @input="handleInput('iceWeight', spec, 3000)"
                    @blur="handleBlur('iceWeight', spec, 0)"
                  />
                  &emsp;
                  <el-switch
                    v-model="spec.iceSwitch"
                    class="w-[20%]"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
                <el-form-item
                  class="justify-between"
                  :label="t('formulaDetail.teaOutTime')"
                  prop="timeTeaOut"
                >
                  <el-input
                    v-model="spec.timeTeaOut"
                    class="!w-[70%]"
                    :disabled="spec.switchTeaOut == '0'"
                    :maxlength="10"
                    :placeholder="t('formulaDetail.teaOutTimePlaceholder')"
                    @input="handleInput('timeTeaOut', spec, 60)"
                    @blur="handleBlur('timeTeaOut', spec, 0)"
                  />
                  &emsp;
                  <el-switch
                    v-model="spec.switchTeaOut"
                    class="w-[20%]"
                    active-value="1"
                    inactive-value="0"
                    @change="
                      switchTeaOutHandle(
                        item.hxtFormulaDetailList,
                        index,
                        $event
                      )
                    "
                  />
                </el-form-item>
              </el-form>
            </div>

            <div
              v-if="
                spec.detail?.length && !IGNORE_BUSINESS_ID.includes(businessId)
              "
              class="mt-[20px] bg-[#EAF2FC] rounded-[2px] px-[16px] py-[20px]"
            >
              <div class="text-[#242930]">
                {{ t("formulaDetail.stirTime") }}
              </div>
              <div>
                <el-form
                  v-for="(stir, stirIndex) in spec?.detail"
                  :key="stirIndex"
                  :model="stir"
                  :rules="stirRules"
                  class="formula-inForm"
                  inline
                  label-width="106px"
                  label-position="left"
                >
                  <el-form-item
                    :label="
                      t('formulaDetail.stirStartTime', { index: stirIndex + 1 })
                    "
                    prop="begin"
                  >
                    <el-input
                      v-model="stir.begin"
                      :placeholder="t('formulaDetail.stirStartTimePlaceholder')"
                      :maxlength="10"
                      @input="handleTimeInput('begin', stir, $event)"
                      @blur="
                        handleStirChange(
                          spec,
                          spec.detail,
                          stir.begin,
                          stirIndex,
                          'begin'
                        )
                      "
                    />
                  </el-form-item>
                  <el-form-item
                    :label="t('formulaDetail.stirEndTime')"
                    prop="time"
                  >
                    <el-input
                      v-model="stir.time"
                      class="!w-[calc(100%_-_50px)]"
                      :placeholder="t('formulaDetail.stirEndTimePlaceholder')"
                      :maxlength="10"
                      @input="handleTimeInput('time', stir, $event)"
                      @blur="
                        handleStirChange(
                          spec,
                          spec.detail,
                          stir.time,
                          stirIndex,
                          'time'
                        )
                      "
                    />

                    <el-button
                      link
                      class="!text-[#EA2626] !text-[12px] w-[50px] text-right"
                      @click="removeStir(spec, stirIndex)"
                    >
                      <FontIcon style="font-size: 14px" icon="icon-delete" />
                      <span class="inline-block align-middle"
                        >&nbsp;{{ t("buttons.delete") }}</span
                      >
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-link
                style="font-size: 14px"
                type="primary"
                :underline="false"
                @click="addStir(spec)"
              >
                <FontIcon icon="icon-plus" />
                <span class="inline-block align-middle"
                  >&nbsp;{{ t("formulaDetail.addStirTime") }}</span
                >
              </el-link>
            </div>
          </div>
        </el-scrollbar>
        <div class="text-center mt-2 px-[20px]">
          <el-button
            class="w-full !h-[46px] !text-[--el-color-primary] font-[500] !text-[14px] disabled:!text-[--autata-font-gray-color]"
            color="#F5F9FF"
            :disabled="item.hxtFormulaDetailList.length > 2"
            @click="addSpec(item)"
          >
            <FontIcon icon="icon-plus2" /> &nbsp;
            {{ t("formulaDetail.addSection") }}
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </AuModal>
</template>

<script setup lang="ts">
import { ref, watch, h, reactive, getCurrentInstance, VNode } from "vue";
import { ElMessage, ElMessageBox, FormRules, TabPaneName } from "element-plus";
import { AuForm } from "@/components/AuForm";
import { AuModal } from "@/components/AuModal";
import { cloneDeep } from "lodash-unified";
import { isArray, isNullOrUnDef, isNumber, isString } from "@pureadmin/utils";
import Edit from "@/assets/svg/edit.svg?component";
import Delete from "@/assets/svg/delete.svg?component";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  addFormula,
  FormulaListProp,
  getFormulaDetail,
  HxtFormulaDetailList,
  HxtFormulaSpecList,
  updFormula
} from "@/api/teaInfuser/formula";
import { userKey } from "@/utils/auth";
import { useI18n } from "vue-i18n";

interface SpecProp {
  waterValue: string;
  temp: string;
  time: string;
  subsectionId: number;
  switchStir: string;
  iceSwitch: string;
  iceWeight: string;
  switchTeaOut: "0" | "1";
  timeTeaOut: string;
  detail?: StirProp[];
}

interface StirProp {
  begin: string;
  time: string;
}

interface SpecListProp {
  specName: string;
  specId: number;
  content: string;
  thirdValue: string;
  materialW: string;
  jbInWater: "0" | "1";
  hxtFormulaDetailList: SpecProp[];
}

const props = defineProps({
  showModal: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object as PropType<FormulaListProp>
  },
  versionId: {
    type: [Number, String]
  }
});
const emit = defineEmits(["update:showModal", "handleConfirm"]);
const { proxy } = getCurrentInstance();
const showDetailModal = ref(props.showModal);
const { t, te } = useI18n();
const formList = ref([
  {
    label: "formulaDetail.name",
    key: "name",
    placeholder: "formulaDetail.namePlaceholder",
    type: "input",
    style: {
      width: "95%"
    },
    required: true,
    span: 12
  },
  {
    label: "formulaDetail.type",
    key: "type",
    placeholder: "formulaDetail.typePlaceholder",
    type: "select",
    required: true,
    span: 12,
    labelKey: "label",
    valueKey: "value",
    clearable: false,
    options: [
      {
        label: "formulaDetail.greenTea",
        value: 1
      },
      {
        label: "formulaDetail.blackTea",
        value: 2
      }
    ],
    defaultValue: 1
  },
  {
    label: "formulaDetail.thirdValue",
    key: "thirdValue",
    placeholder: "formulaDetail.thirdValuePlaceholder",
    type: "input",
    style: {
      width: "95%"
    },
    span: 12
  },
  {
    label: "formulaDetail.noCoverSwitch",
    key: "switchNoCheck",
    type: "el-switch",
    span: 6,
    defaultValue: 0,
    activeValue: 1,
    inactiveValue: 0
  },
  {
    label: "formulaDetail.waterStirSwitch",
    key: "jbInWater",
    type: "el-switch",
    span: 6,
    defaultValue: 0,
    activeValue: 1,
    inactiveValue: 0
  }
]);
const formData = ref({});
const loading = ref(false);
const row = ref({
  formulaId: null
});
const businessId = ref(
  JSON.parse(localStorage.getItem(userKey))?.business_id ?? 0
);
const IGNORE_BUSINESS_ID = ref([92, 93]);

function getHostname() {
  const hostname = window.location.hostname;
  if (hostname === "iotdev.autata.com") {
    IGNORE_BUSINESS_ID.value = [92, 93];
  } else if (hostname === "47.101.185.84") {
    IGNORE_BUSINESS_ID.value = [10001, 10016];
  } else {
    IGNORE_BUSINESS_ID.value = [];
  }
}

getHostname();
let tabIndex = 1;
const editableTabsValue = ref("1");
const timeList: StirProp = { begin: "", time: "" };
const hxtFormulaDetailList: SpecProp = {
  subsectionId: 1,
  waterValue: "",
  temp: "",
  time: "",
  switchStir: "0",
  iceSwitch: "0",
  iceWeight: "",
  switchTeaOut: "0",
  timeTeaOut: "",
  detail: []
};

const hxtFormulaSpecDetailList = ref<any[]>([
  {
    specName: "formulaDetail.spec",
    specId: 1,
    content: "",
    thirdValue: "",
    materialW: "",
    hxtFormulaDetailList: [cloneDeep(hxtFormulaDetailList)]
  }
]);

const validator = (
  rule: any,
  value: string,
  callback: any,
  standard: [number, number]
) => {
  if (!/^-?\d+$/.test(value)) {
    callback(new Error(t("formulaDetail.numberInput")));
  } else if (Number(value) <= 0 && standard[0] != 0) {
    callback(new Error(t("formulaDetail.positiveNumber")));
  } else if (Number(value) < standard[0] || Number(value) > standard[1]) {
    callback(
      new Error(
        t("formulaDetail.numberRange", { min: standard[0], max: standard[1] })
      )
    );
  }
};

const specRules = reactive<FormRules<SpecProp>>({
  waterValue: [
    {
      required: true,
      message: t("formulaDetail.timeInput", {
        field: t("formulaDetail.waterVolume")
      }),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: string, callback: any) =>
        validator(rule, value, callback, [100, 5000]),
      trigger: "blur"
    }
  ],
  temp: [
    {
      required: true,
      message: t("formulaDetail.timeInput", {
        field: t("formulaDetail.temperature")
      }),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: string, callback: any) =>
        validator(rule, value, callback, [70, 97]),
      trigger: "blur"
    }
  ],
  time: [
    {
      required: true,
      message: t("formulaDetail.timeInput", {
        field: t("formulaDetail.brewTime")
      }),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: string, callback: any) =>
        validator(rule, value, callback, [60, 3600]),
      trigger: "blur"
    }
  ],
  iceWeight: [
    {
      validator: (rule: any, value: string, callback: any) =>
        validator(rule, value, callback, [0, 3000]),
      trigger: "blur"
    }
  ],
  timeTeaOut: [
    {
      validator: (rule: any, value: string, callback: any) => {
        const validator = (
          rule: any,
          value: string,
          callback: any,
          standard: [number, number]
        ) => {
          if (value && !/^\d*\.?\d{0,1}$/.test(value)) {
            callback(new Error(t("formulaDetail.decimalPoint")));
          } else if (Number(value) <= 0 && standard[0] != 0) {
            callback(new Error(t("formulaDetail.positiveNumber")));
          } else if (
            Number(value) < standard[0] ||
            Number(value) > standard[1]
          ) {
            callback(
              new Error(
                t("formulaDetail.numberRange", {
                  min: standard[0],
                  max: standard[1]
                })
              )
            );
          }
        };
        validator(rule, value, callback, [0, 60]);
      },
      trigger: "blur"
    }
  ]
});

const stirRules = reactive<FormRules<StirProp>>({
  begin: [
    {
      required: true,
      message: t("formulaDetail.timeInput", {
        field: t("formulaDetail.startTime")
      }),
      trigger: "blur"
    }
  ],
  time: [
    {
      required: true,
      message: t("formulaDetail.timeInput", {
        field: t("formulaDetail.endTime")
      }),
      trigger: "blur"
    }
  ]
});

const formHxtRef = ref();
const specFormRef = ref();

const setEditVal = (row: FormulaListProp) => {
  if (row.formulaId) {
    hxtFormulaSpecDetailList.value = [
      ...hxtFormulaSpecDetailList.value,
      ...hxtFormulaSpecDetailList.value
    ];
    loading.value = false;
    getFormulaDetail({ formulaId: row.formulaId })
      .then(res => {
        const { data, code } = res;
        if (code === 200) {
          formData.value = data.hxtFormula;

          let index = 1;
          for (const spec of data.hxtFormulaSpecDetailList) {
            spec.specId = String(index++);
            spec.hxtFormulaDetailList = spec.hxtFormulaDetailList.map(v => {
              const detail = isJsonString(v.detail) ? JSON.parse(v.detail) : [];
              v.detail = detail.map(v => {
                return {
                  begin: v.begin,
                  time: Number(v.time) + Number(v.begin)
                };
              });

              v.switchTeaOut = (
                v.switchTeaOut ? String(v.switchTeaOut) : "0"
              ) as "0" | "1";
              if (v.switchTeaOut == "1") {
                v.timeTeaOut = String(Number(v.timeTeaOut) / 1000);
              }
              return v;
            });
          }

          hxtFormulaSpecDetailList.value = data.hxtFormulaSpecDetailList;
          editableTabsValue.value = data.hxtFormulaSpecDetailList[0].specId;
          tabIndex = data.hxtFormulaSpecDetailList.length;
        }
        loading.value = false;
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

function isJsonString(str: string) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

const reset = () => {
  formData.value = {
    formulaVersion: null,
    version: Number(props.versionId),
    name: "",
    icon: null,
    deviceType: "泡茶机",
    note: null,
    thirdValue: "",
    deleteStatus: 0,
    publishStatus: 1,
    releaseStatus: null,
    switchNoCheck: 0,
    type: 1,
    tagList: null
  };

  hxtFormulaSpecDetailList.value = [
    {
      specName: "formulaDetail.spec",
      specId: "1",
      hxtFormulaDetailList: [cloneDeep(hxtFormulaDetailList)]
    }
  ];
  editableTabsValue.value = "1";

  if (isArray(specFormRef.value)) {
    for (const ele of specFormRef.value) {
      ele.resetFields();
    }
  }
  formHxtRef.value?.reset();
};

const tabsDbClick = (item: SpecListProp) => {
  ElMessageBox.prompt(
    t("formulaDetail.addSpecTitle"),
    t("formulaDetail.title"),
    {
      confirmButtonText: t("buttons.confirm"),
      cancelButtonText: t("buttons.cancel"),
      inputValue: te(item.specName) ? t(item.specName) : item.specName,
      inputPlaceholder: t("formulaDetail.addSpecPlaceholder"),
      inputValidator: (value: string) => {
        return !(!value || value?.trim() === "");
      },
      inputErrorMessage: t("formulaDetail.addSpecError")
    }
  ).then(({ value }) => {
    item.specName = value;
  });
};

const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: "remove" | "add"
) => {
  if (action === "add") {
    ElMessageBox.prompt(
      t("formulaDetail.addSpecTitle"),
      t("formulaDetail.title"),
      {
        confirmButtonText: t("buttons.confirm"),
        cancelButtonText: t("buttons.cancel"),
        inputPlaceholder: t("formulaDetail.addSpecPlaceholder"),
        inputValidator: (value: string) => {
          return !(!value || value?.trim() === "");
        },
        inputErrorMessage: t("formulaDetail.addSpecError")
      }
    )
      .then(({ value }) => {
        const newTabName = ++tabIndex;
        hxtFormulaSpecDetailList.value.push({
          specName: value,
          specId: String(newTabName),
          hxtFormulaDetailList: [cloneDeep(hxtFormulaDetailList)]
        });
        console.log(newTabName);
        editableTabsValue.value = String(newTabName);
      })
      .catch(() => {});
  } else if (action === "remove") {
    const tabs = hxtFormulaSpecDetailList.value;
    let activeName = editableTabsValue.value;
    if (tabs.length === 1) {
      ElMessage({
        type: "warning",
        message: t("formulaDetail.specDelTips")
      });
      return;
    }

    hxtFormulaSpecDetailList.value = tabs
      .filter(tab => tab.specId !== targetName)
      .map((v, i: number) => {
        v.specId = String(i + 1);
        return v;
      });
    tabIndex = hxtFormulaSpecDetailList.value.length;

    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.specId === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.specId;
          }
        }
      });
    } else if (activeName > targetName) {
      activeName = String(tabIndex);
    }

    editableTabsValue.value = activeName;
  }
};

const handleInput = (
  key: string,
  spec: Record<string, any>,
  standard: number
) => {
  // if (!/^[0-9]+$/.test(spec[key])) spec[key] = spec[key].replace(/\D/g, "");
  // if (Number(spec[key]) > standard) spec[key] = standard;
  // if (Number(spec[key]) <= 0) spec[key] = null;
};
const handleBlur = (
  key: string,
  spec: Record<string, any>,
  standard: number
) => {
  // if (spec[key] && Number(spec[key]) < standard) {
  //   spec[key] = standard;
  // }
};
const handleTimeInput = (key: string, stir: StirProp, val: string) => {
  if (!/^[0-9]+$/.test(val)) stir[key] = val.replace(/\D/g, "");
};
const handleStirChange = (
  typeform: Record<string, any>,
  list: Record<string, any>[],
  current: string,
  index: number,
  key: string
) => {
  console.info(typeform.time);
  console.info(list[0].begin);

  function warningReset(message: string) {
    ElMessage({
      message,
      type: "warning"
    });
    list[index][key] = null;
  }

  if (parseInt(current) > parseInt(typeform.time)) {
    warningReset(t("formulaDetail.timeValidation"));
    return;
  }

  if (
    list[index].begin &&
    list[index].time &&
    parseInt(list[index].begin) > parseInt(list[index].time)
  ) {
    warningReset(t("formulaDetail.endTimeValidation"));
    return;
  }

  if (index > 0 && key === "begin") {
    if (
      list[index - 1].time &&
      parseInt(list[index - 1].time) > parseInt(list[index].begin)
    ) {
      warningReset(t("formulaDetail.previousTimeValidation"));
      return;
    }
  }

  if (list.length > 1 && index < list.length - 1 && key === "time") {
    if (parseInt(list[index].time) >= parseInt(list[index + 1].begin)) {
      warningReset(t("formulaDetail.previousTimeValidation"));
      return;
    }
  }
};

const addSpec = (item: SpecListProp) => {
  item.hxtFormulaDetailList.push(cloneDeep(hxtFormulaDetailList));
};
const removeSpec = (item: SpecListProp, i: number) => {
  if (item.hxtFormulaDetailList.length > 1) {
    item.hxtFormulaDetailList.splice(i, 1);
    item.hxtFormulaDetailList = item.hxtFormulaDetailList.map(
      (v, i: number) => {
        v.subsectionId = i + 1;
        return v;
      }
    );
  } else {
    ElMessage({
      message: t("formulaDetail.specSectionWarning"),
      type: "warning"
    });
  }
};

const addStir = (item: SpecProp) => {
  item.detail.push(cloneDeep(timeList));
};
const removeStir = (item: SpecProp, i: number) => {
  if (item.detail.length > 1) {
    item.detail.splice(i, 1);
  } else {
    ElMessage({
      message: t("formulaDetail.stirTimeWarning"),
      type: "warning"
    });
  }
};

const switchStirHandle = (
  item: SpecProp,
  switchStir: string | number | boolean
) => {
  if (switchStir == 1) {
    item.detail = [cloneDeep(timeList)];
    item.detail[0].begin = "1";
    item.detail[0].time = "10";
  } else {
    item.detail = [];
  }
};

const switchTeaOutHandle = (
  items: SpecProp[],
  index: number,
  switchTeaOut: string | number | boolean
) => {
  // if (switchTeaOut == 1 && index === items.length - 1) {
  //   ElMessage.warning("最后一个分段不可配置出茶阀开启时间！");
  //   console.log(items[index]);
  //   items[index].switchTeaOut = "0";
  // }
};

const validate = (
  value: string,
  standard: [number, number],
  isPoint = false
) => {
  return new Promise(resolve => {
    const numRegex = isPoint ? /^\d*\.?\d{0,1}$/ : /^-?\d+$/;
    if (!numRegex.test(value)) {
      resolve({
        check: false,
        message:
          t("formulaDetail.numberInput") +
          (isPoint ? t("formulaDetail.decimalPoint") : "")
      });
    } else if (Number(value) <= 0 && standard[0] != 0) {
      resolve({ check: false, message: t("formulaDetail.positiveNumber") });
    } else if (Number(value) < standard[0] || Number(value) > standard[1]) {
      resolve({
        check: false,
        message: t("formulaDetail.numberRange", {
          min: standard[0],
          max: standard[1]
        })
      });
    } else {
      resolve({ check: true });
    }
  });
};

const checkSpec = {
  waterValue: (value: string, item: SpecProp) => validate(value, [100, 5000]),
  temp: (value: string, item: SpecProp) => validate(value, [70, 97]),
  time: (value: string, item: SpecProp) => validate(value, [60, 3600]),
  iceWeight: (value: string, item: SpecProp) => {
    console.log(value, item);
    if (item.iceSwitch == "0") {
      return { check: true };
    }
    return validate(value, [0, 3000]);
  },
  timeTeaOut: (value: string, item: SpecProp) => {
    return validate(value, [0, 60], true);
  }
};

const detailCheck = (
  v: HxtFormulaDetailList,
  detail: StirProp[]
): Promise<{ check: boolean; message?: string; i?: number }> => {
  return new Promise(resolve => {
    for (let i = 0; i < detail.length; i++) {
      const item = detail[i];
      if (isNaN(parseInt(item.begin)) || isNaN(parseInt(item.time))) {
        resolve({
          check: false,
          message: t("formulaDetail.timeInput", {
            field: isNaN(parseInt(item.begin))
              ? t("formulaDetail.startTime")
              : t("formulaDetail.endTime")
          }),
          i: i + 1
        });
      }
      if (parseInt(item.begin) < 0 || parseInt(item.time) < 0) {
        resolve({
          check: false,
          message: t("formulaDetail.negativeTimeError"),
          i: i + 1
        });
      }

      if (parseInt(item.begin) >= parseInt(v.time)) {
        resolve({
          check: false,
          message: t("formulaDetail.stirTimeRangeError"),
          i: i + 1
        });
      }
      if (parseInt(item.time) > parseInt(v.time)) {
        resolve({
          check: false,
          message: t("formulaDetail.stirTimeRangeError"),
          i: i + 1
        });
      }

      if (parseInt(item.time) < parseInt(item.begin)) {
        resolve({
          check: false,
          message: t("formulaDetail.endTimeValidation"),
          i: i + 1
        });
      }
      if (i > 0 && parseInt(detail[i - 1].time) > parseInt(item.begin)) {
        resolve({
          check: false,
          message: t("formulaDetail.previousTimeValidation"),
          i: i + 1
        });
      }
    }
    resolve({ check: true });
  });
};

const check = async () => {
  const formData = await formHxtRef.value.validate();
  if (!formData.check) {
    return false;
  }
  const requiredData = {
    waterValue: t("formulaDetail.waterVolume"),
    temp: t("formulaDetail.temperature"),
    time: t("formulaDetail.brewTime"),
    iceWeight: t("formulaDetail.iceWeight")
  };

  const messageFn = (children: VNode[]) => {
    // return proxy.$auMessageBox.confirm(
    //   () => h("p", { style: "line-height: 2; font-size: 14px" }, children),
    //   "提示",
    //   {
    //     type: "error",
    //     showCancel: false
    //   }
    // )
    return ElMessage.warning({
      message() {
        return h("p", { style: "line-height: 2; font-size: 14px" }, children);
      }
    });
  };

  const message = ({
    v,
    key,
    i,
    errDec
  }: {
    v: HxtFormulaSpecList;
    i: number;
    key: string;
    errDec: string;
  }) => {
    return messageFn([
      h("b", null, v.specName),
      h("span", null, " 中，"),
      h("b", null, ` 第${i + 1}段 `),
      h("span", null, "的 "),
      h("b", null, key),
      h("span", null, errDec)
    ]);
  };
  for (const v of hxtFormulaSpecDetailList.value) {
    for (let i = 0; i < v.hxtFormulaDetailList.length; i++) {
      const spec = v.hxtFormulaDetailList[i];
      for (const key in requiredData) {
        // 检验必填项是否符合rule
        const check = await checkSpec[key](spec[key], spec);
        if (!check.check) {
          message({ v, i, key: requiredData[key], errDec: check.message });
          editableTabsValue.value = v.specId;
          return false;
        }
      }
      // 检查搅拌时间是否出错
      if (spec.detail.length > 0) {
        const detailCheckRes = await detailCheck(spec, spec.detail);
        if (!detailCheckRes.check) {
          // message({ v, i, key: "搅拌时间", errDec: detailCheckRes.message });
          messageFn([
            h("b", null, v.specName),
            h("span", null, " 中，"),
            h("span", null, ` 第${i + 1}段 `),
            h("span", null, "的 "),
            h("b", null, "搅拌时间"),
            h("span", null, ` 第${detailCheckRes.i}条 `),
            h("b", null, detailCheckRes.message)
          ]);
          return false;
        }
      }
    }
  }
  return true;
};

const handleConfirm = async () => {
  if (await check()) {
    const hxtFormula = formHxtRef.value.getFormData();
    const hxtFormulaSpecData = cloneDeep(hxtFormulaSpecDetailList.value);
    for (const spec of hxtFormulaSpecData) {
      spec.hxtFormulaDetailList = spec.hxtFormulaDetailList.map(
        (v: any, i: number) => {
          v.subsectionId = i + 1;
          const detailHandle = v.detail.map((detail: StirProp) => {
            return {
              begin: detail.begin,
              time: Number(detail.time) - Number(detail.begin)
            };
          });
          v.detail = JSON.stringify(detailHandle);
          if (v.switchTeaOut == "1") {
            v.timeTeaOut = Number(v.timeTeaOut) * 1000;
          }
          return v;
        }
      );
    }

    console.log(hxtFormula, hxtFormulaSpecData, formData);
    let service = hxtFormula.formulaId ? updFormula : addFormula;

    service({ hxtFormula, hxtFormulaSpecDetailList: hxtFormulaSpecData }).then(
      res => {
        if (res.code === 200) {
          ElMessage({
            message: t("formulaDetail.saveSuccess"),
            type: "success"
          });
          close();
          emit("handleConfirm", res.data);
        }
      }
    );
  }
};

const close = () => {
  reset();
  emit("update:showModal", false);
};

watch(
  () => [props.showModal, props.rowData],
  ([val, row]) => {
    showDetailModal.value = val;
    if (val) {
      if (!row.id) {
        row.value = { formulaId: null };
        reset();
      } else {
        row.value = row;
        setEditVal(row);
      }
    }
  }
);
</script>

<style scoped>
.demo-tabs {
  :deep(.el-tabs__nav-wrap::after) {
    height: 0;
  }

  :deep(.el-tabs__header) {
    padding: 0 20px;
    margin: 0;
    box-shadow: inset 0 -1px 0 0 #eaebef;

    .el-tabs__new-tab {
      width: auto;
      border: none;
    }
  }

  :deep(.el-tabs__content) {
    width: 100%;
  }
}

.formula-form {
  :deep(.el-form) {
    display: flex;
    justify-content: space-between;
    width: 100%;

    .el-row {
      justify-content: space-between;
      width: 100%;
    }
  }
}

.formula-inForm {
  :deep(.el-form-item) {
    width: calc(50% - 16px);
    margin-right: 16px;
    margin-bottom: 16px;
  }
}

.required {
  &::before {
    margin-right: 4px;
    color: #ff4949;
    content: "*";
  }
}
</style>
